import { login, singleLogin, getUsername } from '@/api/dashboard.js';
import { getToken, setToken, removeToken } from '@/utils/auth';
import router, { resetRouter } from '@/router';
import store from '@/store';
import { perdatagrid, getTxnOppoType } from '@/api/sys/seting';
import selectOptions from '@/utils/selectOptions.js';
import moment from 'moment';
import { getUrlParam } from '@/utils/common.js';
import axios from 'axios';
import { Message } from 'element-ui';

const state = {
  token: getToken(),
  userame: '',
  userId: '',
  userInfo: {},
  customerInfo: {},
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_USERID: (state, userInfo) => {
    state.userId = userId;
  },
  SET_USERNAME: (state, userInfo) => {
    state.username = username;
  },
  SET_CUSTOMERINFO: (state, customerInfo) => {
    state.customerInfo = customerInfo;
  },
};

const actions = {
  async getUserInfoByToken({ commit, dispatch }, token) {
    const kdpUserUrl = `${process.env.VUE_APP_KDP_BASE_URL}/user/getUserInfo`;
    const kdpUserRes = await axios.get(kdpUserUrl);
    if (kdpUserRes.code === 200) {
      commit('SET_USERINFO', kdpUserRes.data.userInfo);
      commit('SET_USERID', kdpUserRes.data.userInfo.id);
      commit('SET_USERNAME', kdpUserRes.data.userInfo.name);
    } else {
      Message.error('获取用户信息失败');
    }
  },
  // old
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        userName: username.trim(),
        password: password,
      })
        .then((response) => {
          if (response.success === true) {
            //   const { data, token } = response
            commit('SET_TOKEN', moment().format('YYYY-MM-DD HH:mm:ss'));
            setToken(moment().format('YYYY-MM-DD HH:mm:ss'));
            resolve(response);
          } else {
            resolve(response);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
